package com.lin.mr.maizilaundry.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lin.mr.maizilaundry.R;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import zhy.com.highlight.HighLight;

public class LoginActivity extends Activity implements View.OnClickListener{
    private ImageView btn_back_login;
    private TextView btn_to_register;
    private EditText et_phone_number;
    //发送短信验证码的按钮
    private Button btn_Captcha;
    private EditText et_Captcha;
    private Button btn_login;
    private TextView tv_agreement;
    private LinearLayout register_layout;

    private HighLight highLight;
    private Boolean isNumber;

    private CountTimer countTimer;
    private EventHandler eh;//将EvenHandler的对象声明为全局
    private void initViews() {
        //初始化控件
        btn_back_login = (ImageView) findViewById(R.id.btn_back_login);
        btn_to_register = (TextView) findViewById(R.id.btn_to_register);
        et_phone_number = (EditText) findViewById(R.id.et_phone_number);
        btn_Captcha = (Button) findViewById(R.id.btn_captcha);
        et_Captcha = (EditText) findViewById(R.id.et_captcha);
        btn_login = (Button) findViewById(R.id.btn_login);
        tv_agreement = (TextView) findViewById(R.id.tv_agreement);
        register_layout = (LinearLayout) findViewById(R.id.register_layout);

        countTimer = new CountTimer(60000,1000);

        //设置监听事件
        tv_agreement.setOnClickListener(this);
        btn_Captcha.setOnClickListener(this);
        btn_back_login.setOnClickListener(this);
        btn_to_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);

        //必须用post方法通知更新线程，否则会报空指针
        btn_to_register.post(new Runnable() {
            @Override
            public void run() {
                tipForRegister();
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //初始化短信验证
        SMSSDK.initSDK(this,"14a365521aca6","dc9b909f12ae00b594213ea955389e3c");

//        EventHandler eh=new EventHandler(){
//
//            @Override
//            public void afterEvent(int event, int result, Object data) {
//
//                Message msg = new Message();
//                msg.arg1 = event;
//                msg.arg2 = result;
//                msg.obj = data;
//                handler.sendMessage(msg);
//            }
//        };
        initViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除短信验证码注册
        if (eh != null){
            SMSSDK.unregisterEventHandler(eh);
            Log.e("SMS","当前没有绑定短信注册");
        }
        countTimer.cancel();//关闭倒计时
    }

    // 判断用户输入的手机号码是否正确
    public boolean isPhoneNumber(String str) {
        String strRegex = "[1][34578]\\d{9}";
        boolean result = str.matches(strRegex);
        return result;
    }

    @Override
    public void onClick(View v) {
        String phoneNum = et_phone_number.getText().toString().trim();//获取手机号码
        String captcha = et_Captcha.getText().toString().trim();//获取验证码
        switch (v.getId()){
            case R.id.btn_to_register:
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
                break;
            case R.id.btn_captcha: //发送验证码
                isNumber = isPhoneNumber(phoneNum);
                if (isNumber==true){
                    countTimer.start();//点击按钮开始倒计时
                    sendSMSCaptcha();//发送验证码
                }else {
                    et_phone_number.setError(Html.fromHtml("<font color=red>您输入的手机号码有误！</font>"));
                    Toast.makeText(this, "您输入的手机号码有误o(╯□╰)o", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_agreement:
                startActivity(new Intent(LoginActivity.this,WebViewActivity.class));
                break;
            case R.id.btn_back_login:
                finish();
                break;
            case R.id.btn_login:
                if (!TextUtils.isEmpty(captcha)){//判断验证码是否为空
                    if (captcha.length()==4){//判断验证码是否为4位
                        //向服务器提交接收到的短信验证码，验证成功后会通过EventHandler返回国家代码和电话号码
                        SMSSDK.submitVerificationCode("86", et_phone_number.getText().toString().trim(),
                                captcha);
                    }else {
                        et_Captcha.setError(Html.fromHtml("<font color=red>验证码输入有误！</font>"));
                    }
                }else {
                    et_Captcha.setError(Html.fromHtml("<font color=red>请输入验证码！</font>"));
                }

                break;
        }
    }
    //发送短信验证码
    private void sendSMSCaptcha() {

        EventHandler eh=new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };

        SMSSDK.registerEventHandler(eh); //注册短信回调
        //向服务器请求发送验证码的服务，需要传递国家代号和接收验证码的手机号码
        SMSSDK.getVerificationCode("86",et_phone_number.getText().toString());
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    Toast.makeText(LoginActivity.this, "验证码正确", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginActivity.this,HomeActivity.class));

                }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    //获取验证码成功
                    Toast.makeText(LoginActivity.this, "验证码已经发送", Toast.LENGTH_SHORT).show();
                }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
                    //返回支持发送验证码的国家列表
                }
            }else{
                ((Throwable)data).printStackTrace();
                Toast.makeText(LoginActivity.this, "验证码获取失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    //发送验证码之后进行60s倒计时
    public class CountTimer extends CountDownTimer{

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //倒计时期间调用的方法
        @Override
        public void onTick(long millisUntilFinished) {
            btn_Captcha.setText(millisUntilFinished/1000+"秒后重新发送");
            btn_Captcha.setTextSize(14);//将按钮上的文字字体修改小一点
            btn_Captcha.setClickable(false);
        }

        //倒计时结束之后回调的方法
        @Override
        public void onFinish() {
            btn_Captcha.setText("重新发送");
            btn_Captcha.setClickable(true);
        }
    }

    //对注册按钮进行高亮提示
    public void tipForRegister(){
        highLight = new HighLight(LoginActivity.this);
        highLight.anchor(register_layout);//指明需要加上透明蒙版的view
        highLight.addHighLight(R.id.btn_to_register, R.layout.tip_register, new HighLight.OnPosCallback() {
            @Override
            public void getPos(float rightMargin, float bottomMargin, RectF rectF, HighLight.MarginInfo marginInfo) {
                //下面两行不是很明白
                /**
                 * @param rightMargin 高亮view在anchor中的右边距
                 * @param bottomMargin 高亮view在anchor中的下边距
                 * @param rectF 高亮view的l,t,r,b,w,h都有
                 * @param marginInfo 设置你的布局的位置，一般设置l,t或者r,b
                 */
                marginInfo.rightMargin = rightMargin;
                marginInfo.topMargin = rectF.top + rectF.height();
            }
        });
        highLight.show();
    }
}
